package cn.kgc;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author wangyue
 * @version 1.0
 */
public class Demo6 {
    //创建线程数固定的线程池
    private static ExecutorService executorService= Executors.newFixedThreadPool(10);

    public static void main(String[] args) {
        m2();
    }

    private static void m2() {
        CompletableFuture<String> future1= CompletableFuture.supplyAsync(()->{
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            String name = Thread.currentThread().getName();
            System.out.println("异步任务1执行完成，当前线程名称："+name);
            return name;
        },executorService);

        CompletableFuture<String> future2= CompletableFuture.supplyAsync(()->{
            String name = Thread.currentThread().getName();
            System.out.println("异步任务2执行完成，当前线程名称："+name);
            return name;
        },executorService);

        CompletableFuture<String> future3= CompletableFuture.supplyAsync(()->{
            System.out.println("异步任务3执行完成，当前线程名称："+Thread.currentThread().getName());
            return "任务3的返回值";
        },executorService);

        //任务1  任务2  任务3中的任意一个任务执行完 就接着向下执行
        CompletableFuture.anyOf(future1,future2,future3).join();
        System.out.println("main方法接着向下执行");
        //关闭线程池
        executorService.shutdown();
    }

    private static void m1() {
        CompletableFuture<String> future1= CompletableFuture.supplyAsync(()->{
            try {
                Thread.sleep(2000); //线程休眠2s
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            String name = Thread.currentThread().getName();
            System.out.println("异步任务1执行完成，当前线程名称："+name);
            return name;
        },executorService);

        CompletableFuture<String> future2= CompletableFuture.supplyAsync(()->{
            String name = Thread.currentThread().getName();
            System.out.println("异步任务2执行完成，当前线程名称："+name);
            return name;
        },executorService);

        CompletableFuture<String> future3= CompletableFuture.supplyAsync(()->{
            System.out.println("异步任务3执行完成，当前线程名称："+Thread.currentThread().getName());
            return "任务3的返回值";
        },executorService);

        //等待任务1 任务2 任务3 都执行完成
        CompletableFuture.allOf(future1,future2,future3).join();
        System.out.println("main方法接着向下执行");

        //关闭线程池
        executorService.shutdown();
    }
}